package com.dongjiantong.quarantine.serviceImpl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.dongjiantong.biz.enums.ReportType;
import com.dongjiantong.biz.model.EarMarkLife;
import com.dongjiantong.biz.model.ReportHandleResumes;
import com.dongjiantong.biz.service.EarMarkLifeWriteService;
import com.dongjiantong.biz.service.ReportHandleResumesService;
import com.dongjiantong.common.utils.ReportNumberMakerUtil;
import com.dongjiantong.common.web.sso.LoginInfo;
import com.dongjiantong.mybatis.ServiceMybatis;
import com.dongjiantong.quarantine.enums.FileType;
import com.dongjiantong.quarantine.enums.HarmlessStatus;
import com.dongjiantong.quarantine.mapper.BreedReportsFileMapper;
import com.dongjiantong.quarantine.mapper.DjtButcherAdmissionInspectionsMapper;
import com.dongjiantong.quarantine.mapper.HarmlessMapper;
import com.dongjiantong.quarantine.model.BreedReportsFile;
import com.dongjiantong.quarantine.model.DjtButcherAdmissionInspections;
import com.dongjiantong.quarantine.model.Harmless;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by mz on 15/11/17.
 */
@Slf4j
@Service(version = "1.0.0")
public class DjtButcherAdmissionInspectionsWriteServiceImpl extends ServiceMybatis<DjtButcherAdmissionInspections> implements DjtButcherAdmissionInspectionsWriteService {

    @Resource
    private DjtButcherAdmissionInspectionsMapper djtButcherAdmissionInspectionsMapper;

    @Resource
    private HarmlessMapper harmlessMapper;

    @Reference(version = "1.0.0")
    private EarMarkLifeWriteService earMarkLifeWriteService;

    @Resource
    private BreedReportsFileMapper breedReportsFileMapper;

    @Reference(version = "1.0.0")
    private ReportHandleResumesService reportHandleResumesService;

    /**
     * 创建入场监督检查单据
     *
     * @param djtButcherAdmissionInspections 单据对象
     * @param toStatus                       到状态
     * @return Map<String , Object>
     */
    @Override
    public Map<String, Object> create(DjtButcherAdmissionInspections djtButcherAdmissionInspections, Integer toStatus,LoginInfo loginInfo) {

        Integer fromStatus = djtButcherAdmissionInspections.getStatus().intValue();
        Map<String, Object> resultMap = Maps.newHashMap();
        String prefix = "S";
        prefix = ReportNumberMakerUtil.createPrefix(prefix,loginInfo.getProvinceId(),loginInfo.getCityId(),loginInfo.getRegionId());//单据编号前缀的开头字母 和 当前用户
        String number = ReportNumberMakerUtil.create(prefix, djtButcherAdmissionInspectionsMapper.findCurrentMaxNumber(prefix));
        djtButcherAdmissionInspections.setNumber(number);
        if (toStatus != null && !fromStatus.equals(toStatus)) {
            djtButcherAdmissionInspections.setStatus(toStatus.byteValue());
            djtButcherAdmissionInspectionsMapper.insert(djtButcherAdmissionInspections);
            ReportHandleResumes reportHandleResumes = new ReportHandleResumes();

            reportHandleResumes.setFrom_status(fromStatus.byteValue());
            reportHandleResumes.setReport_id(djtButcherAdmissionInspections.getId());
            reportHandleResumes.setReport_number(number);
            reportHandleResumes.setTo_status(toStatus.byteValue());
            reportHandleResumes.setType(ReportType.ADMISSION_INSPECTION.value());
            reportHandleResumes.setCreated_at(new Date());
            reportHandleResumes.setUpdated_at(new Date());

            reportHandleResumesService.create(reportHandleResumes);
            if (djtButcherAdmissionInspections.getUnqualified_quantity() > 0) {
                Harmless harmless = buildHarmless(djtButcherAdmissionInspections,loginInfo);
                harmlessMapper.insert(harmless);
                resultMap.put("harmlessId", harmless.getId());

                djtButcherAdmissionInspections.setHarmless_id(harmless.getId());
                djtButcherAdmissionInspections.setHarmless_number(harmless.getNumber());
                djtButcherAdmissionInspectionsMapper.updateByPrimaryKey(djtButcherAdmissionInspections);
            }
            insertToEarLife(djtButcherAdmissionInspections,loginInfo);
        } else {
            djtButcherAdmissionInspectionsMapper.insert(djtButcherAdmissionInspections);
        }
        Integer isLocal = djtButcherAdmissionInspections.getIs_local();
        if (isLocal == -1) {
            List<String> quarantine_cert_photo_list = djtButcherAdmissionInspections.getQuarantine_cert_photo_list();
            if (quarantine_cert_photo_list != null && !quarantine_cert_photo_list.isEmpty()) {
                writeFiles(ReportType.ADMISSION_INSPECTION.value(), FileType.PHOTO.value(), djtButcherAdmissionInspections.getId(), quarantine_cert_photo_list, "quarantine_cert_photo_list", "入场监督检查");
            }
        }
        resultMap.put("id", djtButcherAdmissionInspections.getId());
        return resultMap;
    }

    /**
     * 更新单据
     *
     * @param djtButcherAdmissionInspections 单据对象
     * @param toStatus                       到状态
     * @return Map<String , Object>
     */
    @Override
    public Map<String, Object> update(DjtButcherAdmissionInspections djtButcherAdmissionInspections, Integer toStatus, LoginInfo loginInfo) {
        Integer fromStatus = djtButcherAdmissionInspections.getStatus().intValue();

        Boolean isSuccess;

        Map<String, Object> resultMap = Maps.newHashMap();
        if (toStatus != null && !fromStatus.equals(toStatus)) {
            djtButcherAdmissionInspections.setStatus(toStatus.byteValue());
            isSuccess = (long) djtButcherAdmissionInspectionsMapper.updateByPrimaryKey(djtButcherAdmissionInspections) == 1;
            ReportHandleResumes reportHandleResumes = new ReportHandleResumes();

            reportHandleResumes.setFrom_status(fromStatus.byteValue());
            reportHandleResumes.setReport_id(djtButcherAdmissionInspections.getId());
            reportHandleResumes.setReport_number(djtButcherAdmissionInspections.getNumber());
            reportHandleResumes.setTo_status(toStatus.byteValue());
            reportHandleResumes.setType(ReportType.ADMISSION_INSPECTION.value());
            reportHandleResumes.setCreated_at(new Date());
            reportHandleResumes.setUpdated_at(new Date());

            reportHandleResumesService.create(reportHandleResumes);
            if (djtButcherAdmissionInspections.getUnqualified_quantity() > 0) {
                Harmless harmless = buildHarmless(djtButcherAdmissionInspections, loginInfo);
                harmlessMapper.insert(harmless);
                resultMap.put("harmlessId", harmless.getId());
                djtButcherAdmissionInspections.setHarmless_id(harmless.getId());
                djtButcherAdmissionInspections.setHarmless_number(harmless.getNumber());
                djtButcherAdmissionInspectionsMapper.updateByPrimaryKey(djtButcherAdmissionInspections);
            }
            insertToEarLife(djtButcherAdmissionInspections,loginInfo);
        } else {
            isSuccess = (long) djtButcherAdmissionInspectionsMapper.updateByPrimaryKey(djtButcherAdmissionInspections) == 1;
        }
        resultMap.put("isSuccess", isSuccess);
        return resultMap;
    }

    /**
     * 根据id 更新单据的有效状态
     *
     * @param admissionId 单据id
     */
    @Override
    public void updateDeleteFlag(Long admissionId) {
        djtButcherAdmissionInspectionsMapper.updateDeleteFlag(admissionId);
    }

    /**
     * 无害化
     *
     * @param djtButcherAdmissionInspections 单据对象
     * @return Harmless
     */
    private Harmless buildHarmless(DjtButcherAdmissionInspections djtButcherAdmissionInspections, LoginInfo loginInfo) {
        Harmless harmless = new Harmless();

        Integer isLocal = djtButcherAdmissionInspections.getIs_local();
        String prefix = "WBD";
        if (!isLocal.equals(1)) {
            prefix = "WWD";
        }
        prefix = ReportNumberMakerUtil.createPrefix(prefix, loginInfo.getProvinceId(),loginInfo.getCityId(),loginInfo.getRegionId());
        String number = ReportNumberMakerUtil.create(prefix, harmlessMapper.findCurrentMaxNumber(prefix));
        harmless.setNumber(number);
        harmless.setStatus(HarmlessStatus.UNCOMMITTED.value());
        harmless.setQuarantine_user_id(loginInfo.getId());
        harmless.setQuarantine_user_name(loginInfo.getRealName());
        harmless.setUnit(djtButcherAdmissionInspections.getUnit());
        harmless.setIs_local(isLocal);
        harmless.setButcher_farm_id(djtButcherAdmissionInspections.getButcher_farm_id().longValue());
        harmless.setButcher_farm_name(djtButcherAdmissionInspections.getButcher_farm_name());
        harmless.setReport_type(ReportType.ADMISSION_INSPECTION.value());
        harmless.setReport_id(djtButcherAdmissionInspections.getId());
        harmless.setReport_number(djtButcherAdmissionInspections.getNumber());
        harmless.setAnimal_type(djtButcherAdmissionInspections.getProduct_type());
//        harmless.setAnimal_type_name(djtButcherAdmissionIns);
        harmless.setFactory_owner_name(djtButcherAdmissionInspections.getOwner());
        harmless.setQuantity(djtButcherAdmissionInspections.getUnqualified_quantity().floatValue());
        harmless.setDelete_flag(1);
        harmless.setCreated_at(new Date());
        harmless.setUpdated_at(new Date());
        return harmless;
    }

    /**
     * 耳标使用记录的写入
     *
     * @param djtButcherAdmissionInspections 入场监督检查的对象
     */
    private void insertToEarLife(DjtButcherAdmissionInspections djtButcherAdmissionInspections, LoginInfo loginInfo) {
        List<String> earTagNumbers = djtButcherAdmissionInspections.getEar_tag_numbers();
        List<EarMarkLife> earMarkLives = null;
        if (earTagNumbers != null) {
            for (String earTagNumber : earTagNumbers) {
                earMarkLives = new ArrayList<>();
                EarMarkLife earMarkLife = new EarMarkLife();
                earMarkLife.setMark_number(earTagNumber);
                earMarkLife.setReport_id(djtButcherAdmissionInspections.getId());
                earMarkLife.setReport_name(djtButcherAdmissionInspections.getNumber());
                earMarkLife.setReport_type(ReportType.ADMISSION_INSPECTION.value());
                earMarkLife.setMark_type(djtButcherAdmissionInspections.getProduct_type());
                earMarkLife.setOperator_id(loginInfo.getId());
                earMarkLife.setOperator_name(loginInfo.getRealName());
                earMarkLife.setIs_selected(1);
                earMarkLife.setCreated_at(new Date());
                earMarkLives.add(earMarkLife);
            }
            if (earMarkLives != null && !earMarkLives.isEmpty()) earMarkLifeWriteService.insertList(earMarkLives);
        }
    }

    /**
     * 图片或文件的写入
     *
     * @param fileUrls 照片的url
     * @param field    字段名
     * @param state    意义
     */
    private void writeFiles(Integer type1, Integer type2, Long relevanceId, List<String> fileUrls, String field, String state) {
        if (fileUrls != null && !fileUrls.isEmpty()) {
            for (String string : fileUrls) {
                BreedReportsFile breedReportsFile = new BreedReportsFile();
                breedReportsFile.setType1(type1);
                breedReportsFile.setType2(type2);
                breedReportsFile.setField(field);
                breedReportsFile.setAddress(string);
                breedReportsFile.setRelevance_id(relevanceId);
                breedReportsFile.setState(state);
                breedReportsFile.setDate(new Date());
                breedReportsFileMapper.insert(breedReportsFile);
            }
        }
    }

}
